import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

export interface ModelProvider {
  id: string
  name: string
  models: ModelInfo[]
  hasApiKey: boolean
  isActive: boolean
  apiKey?: string
  baseURL?: string
}

export interface ModelInfo {
  id: string
  name: string
  description?: string
  maxTokens: number
  costPer1K?: number
}

export interface ModelConfig {
  provider: string
  model: string
  temperature: number
  maxTokens: number
  topP?: number
  frequencyPenalty?: number
  presencePenalty?: number
}

export const useModelConfigStore = defineStore('modelConfig', () => {
  // 当前全局模型配置
  const globalConfig = reactive<ModelConfig>({
    provider: 'qwen',
    model: 'qwen-plus-latest',
    temperature: 0.7,
    maxTokens: 2000,
    topP: 0.9,
    frequencyPenalty: 0,
    presencePenalty: 0
  })

  // 可用的模型提供商
  const providers = reactive<Record<string, ModelProvider>>({
    qwen: {
      id: 'qwen',
      name: 'Qwen Plus Latest',
      hasApiKey: false,
      isActive: true,
      models: [
        {
          id: 'qwen-plus-latest',
          name: 'Qwen Plus Latest',
          description: '通义千问最新版本',
          maxTokens: 8000,
          costPer1K: 0.002
        },
        {
          id: 'qwen-turbo-latest',
          name: 'Qwen Turbo Latest',
          description: '通义千问快速版本',
          maxTokens: 8000,
          costPer1K: 0.001
        }
      ]
    },
    doubao: {
      id: 'doubao',
      name: 'Doubao Seed 1.6',
      hasApiKey: false,
      isActive: false,
      models: [
        {
          id: 'doubao-seed-1-6-250615',
          name: 'Doubao Seed 1.6',
          description: '字节跳动豆包模型',
          maxTokens: 8000,
          costPer1K: 0.0015
        }
      ]
    },
    deepseek: {
      id: 'deepseek',
      name: 'DeepSeek R1',
      hasApiKey: false,
      isActive: false,
      models: [
        {
          id: 'deepseek-reasoner',
          name: 'DeepSeek Reasoner',
          description: 'DeepSeek推理模型',
          maxTokens: 8000,
          costPer1K: 0.0008
        },
        {
          id: 'deepseek-chat',
          name: 'DeepSeek Chat',
          description: 'DeepSeek对话模型',
          maxTokens: 8000,
          costPer1K: 0.0008
        }
      ]
    }
  })

  // API密钥存储
  const apiKeys = reactive<Record<string, string>>({})

  // 获取当前活跃的提供商
  const getCurrentProvider = () => {
    return providers[globalConfig.provider]
  }

  // 获取当前模型信息
  const getCurrentModel = () => {
    const provider = getCurrentProvider()
    return provider?.models.find(m => m.id === globalConfig.model)
  }

  // 设置全局配置
  const setGlobalConfig = (config: Partial<ModelConfig>) => {
    Object.assign(globalConfig, config)
    localStorage.setItem('globalModelConfig', JSON.stringify(globalConfig))
  }

  // 设置API密钥
  const setApiKey = (providerId: string, apiKey: string) => {
    apiKeys[providerId] = apiKey
    providers[providerId].hasApiKey = !!apiKey
    providers[providerId].apiKey = apiKey
    
    localStorage.setItem('modelApiKeys', JSON.stringify(apiKeys))
  }

  // 设置活跃的提供商
  const setActiveProvider = (providerId: string) => {
    // 取消所有提供商的活跃状态
    Object.values(providers).forEach(provider => {
      provider.isActive = false
    })
    
    // 设置新的活跃提供商
    if (providers[providerId]) {
      providers[providerId].isActive = true
      globalConfig.provider = providerId
      
      // 如果当前模型不属于新提供商，则切换到该提供商的第一个模型
      const newProvider = providers[providerId]
      const currentModelExists = newProvider.models.some(m => m.id === globalConfig.model)
      if (!currentModelExists && newProvider.models.length > 0) {
        globalConfig.model = newProvider.models[0].id
      }
      
      localStorage.setItem('globalModelConfig', JSON.stringify(globalConfig))
    }
  }

  // 测试模型连接
  const testConnection = async (providerId: string) => {
    const provider = providers[providerId]
    if (!provider || !provider.hasApiKey) {
      throw new Error('API密钥未配置')
    }
    
    try {
      // 动态导入AI服务，避免循环依赖
      const { aiService } = await import('@/services/aiService')
      const result = await aiService.testConnection(providerId)
      
      return {
        success: result.success,
        message: result.message,
        latency: result.latency || 0
      }
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : '连接测试失败'
      }
    }
  }

  // 获取提供商状态
  const getProviderStatus = () => {
    const status: Record<string, any> = {}
    Object.entries(providers).forEach(([id, provider]) => {
      status[id] = {
        hasApiKey: provider.hasApiKey,
        isActive: provider.isActive,
        name: provider.name
      }
    })
    return status
  }

  // 初始化：从localStorage加载配置
  const initConfig = () => {
    try {
      const savedConfig = localStorage.getItem('globalModelConfig')
      if (savedConfig) {
        const config = JSON.parse(savedConfig)
        Object.assign(globalConfig, config)
      }
      
      const savedApiKeys = localStorage.getItem('modelApiKeys')
      if (savedApiKeys) {
        const keys = JSON.parse(savedApiKeys)
        Object.assign(apiKeys, keys)
        
        // 更新提供商的API密钥状态
        Object.entries(keys).forEach(([providerId, apiKey]) => {
          if (providers[providerId] && apiKey) {
            providers[providerId].hasApiKey = true
            providers[providerId].apiKey = apiKey as string
          }
        })
      }
    } catch (error) {
      console.warn('Failed to load model config from localStorage:', error)
    }
  }

  // 导出配置
  const exportConfig = () => {
    return {
      globalConfig: { ...globalConfig },
      apiKeys: { ...apiKeys },
      providers: JSON.parse(JSON.stringify(providers))
    }
  }

  // 导入配置
  const importConfig = (config: any) => {
    if (config.globalConfig) {
      Object.assign(globalConfig, config.globalConfig)
    }
    if (config.apiKeys) {
      Object.assign(apiKeys, config.apiKeys)
    }
    if (config.providers) {
      Object.assign(providers, config.providers)
    }
    
    localStorage.setItem('globalModelConfig', JSON.stringify(globalConfig))
    localStorage.setItem('modelApiKeys', JSON.stringify(apiKeys))
  }

  return {
    globalConfig,
    providers,
    apiKeys,
    getCurrentProvider,
    getCurrentModel,
    setGlobalConfig,
    setApiKey,
    setActiveProvider,
    testConnection,
    getProviderStatus,
    initConfig,
    exportConfig,
    importConfig
  }
})